import json

from django.http import HttpResponse

from MyModel.models import Test
from utils import time_util


def test_insert_db(request):
    birth = time_util.time_to_string('%Y-%m-%d')
    create = time_util.time_to_string(format_=None)
    test1 = Test(s_name='张三', s_birth=birth, s_sex='男', s_create=create)
    test1.save()
    return HttpResponse('<p>数据添加成功！</p>')


def test_object(request):
    obj = Test.objects
    # 查询
    t1 = obj.get(id=1)
    # obj.filter(id=1)
    print(f'id=1的数据:{t1.s_name}')
    # 更新
    t1.s_name = "Google"
    # obj.filter(id=1).update(s_name='Baidu')
    t1.save()

    # 插入
    t = time_util.time_to_string(format_=None)
    data = Test(s_name='Apple', s_birth='1995-09-19', s_sex='男', s_create=t)
    data.save()
    # print(f"===========插入后的返回值:{r}=============")

    # 删除
    t2 = obj.filter(id=1)
    print(f"修改后查询数据(id=1):{t2.model}")
    # obj.filter(id=1).delete()
    t2.delete()
    return HttpResponse('<p>Object操作！</p>')
